<?php

namespace app\api\controller;
use app\BaseController;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class Base extends BaseController {

  public $model;

  protected $middleware = [ 
    \app\api\middleware\Auth::class => ['except' 	=> ['login'] ]
  ];

  public function __call($method, $args) {
    return message(config('status.action_not_found'), '方法未找到', null, 404);
  }

  public function export() {
    if($this->model) {
      $filename = 'table-data.xlsx';
      header('Content-Type: application/vnd.ms-excel');
      header('Content-Disposition: attachment;filename="'.$filename.'"');
      header('Cache-Control: max-age=0');
      $spreadsheet = new Spreadsheet();
      $sheet = $spreadsheet->getActiveSheet();

      $fields = $this->model->getFields();
      foreach ($fields as $key => $value) {
        $sheet->setCellValueByColumnAndRow($key + 1, 1, $value);
      }
      $row = 2; 
      $data = $this->model->getAll();
      foreach($data as $item) {
        $col = 1;
        foreach($item as $value) {
          $sheet->setCellValueByColumnAndRow($col++, $row, $value);
        }   
        $row++;
      }
      $writer = new Xlsx($spreadsheet);
      $data = $writer->save('php://output');
    }
  }

  public function list(\think\Request $request) {
    
    $limit = input('get.limit', config('page.limit'), 'intval');
    $page = input('get.page', 1, 'intval');
    $sort = input('get.sort');
    $key = input('get.key');
    
    if(!empty($sort)) {
      $sortField = substr($sort, 1);
      $sort = $sort[0] == '+' ? $sortField.' asc' : $sortField.' desc';
    }

    $query = [
      'page' => $page,
      'limit' => $limit,
      'order' => $sort,
      'key' => $key
    ];
   
    $result = $this->model->get($query);

    return success([
      'total' => $this->model->count(),
      'items' => $result 
    ]);

  }

  
  public function create() {
    $data = input('post.');
    if(isset($data['create_time'])) {
      $data['create_time']= convertTime($data['create_time']);
    }
    if(!empty($data['id'])) {
      $this->model->update($data);
    } else {
      $this->model->save($data);
    }
    return success();
  }

  public function detail() {
    $id = input('get.id', '', 'intval');
    $data = $this->model->getById($id);
    return success($data);
  }

  public function delete() {
    $id = input('post.id');
    $this->model->deleteById($id);
    return success();
  }

}